package com.mantru.iotpot.Cleaning;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.mantru.iotpot.ApplicationClass;
import com.mantru.iotpot.R;
import com.mantru.iotpot.Tools.tools;
import com.mantru.iotpot.Util.ToastUtils;

public class PotCuringWaitActivity extends AppCompatActivity implements View.OnClickListener {
    private AlertDialog dialog; // 用于存储弹窗对象
    private CountDownTimer timer;
    private Handler handler;
    private Runnable updateRunnable;
    private TextView name;
    private TextView time;
    private Button stop;
    private LinearLayout box;
    private Button back;
    private Button put_oil;
    private ApplicationClass ac;
    private int type;
    private String TAG = "PotCuringWaitActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pot_curing_wait);
        ac = (ApplicationClass) getApplication(); // 初始化 ApplicationClass
        Intent intent = getIntent();
        type = intent.getIntExtra("oil_type", -1);
        Log.d(TAG, "type: " + type);
        initialization();//初始化控件
        String statusText = "";
        if (type == 1) {
            statusText = "快速养锅";
        }
        boolean result = ac.Bringup_Start(1);
        Log.d(TAG,"result: " + result);
//        updateUI();//更新洗锅状态
        if (result) {
            // 创建Handler用于在主线程中更新UI
            handler = new Handler(Looper.getMainLooper());
            updateRunnable = new Runnable() {
                @Override
                public void run() {
                    updateUI();
                    handler.postDelayed(this, 1000); // 每秒刷新一次
                }
            };
            // 开始定时更新UI
            handler.post(updateRunnable);
        } else {
            Toast.makeText(this, "洗锅失败", Toast.LENGTH_SHORT).show();
        }
    }

    //初始化控件
    private void initialization(){
        name = findViewById(R.id.pot_curing_wash_name);
        time = findViewById(R.id.pot_curing_wash_time);
        stop = findViewById(R.id.pot_curing_wash_stop);
        box = findViewById(R.id.pot_curing_LinearLayout);
        back = findViewById(R.id.pot_curing_wash_back);
        put_oil = findViewById(R.id.pot_curing_wash_put_oil);
        stop.setOnClickListener(this);
        back.setOnClickListener(this);
        put_oil.setOnClickListener(this);
    }


    private void updateUI() {
        // 更新洗锅状态
        // 更新剩余时间
        if (ac.jobmaster.steep_status == 2){//洗锅完成
            handler.removeCallbacks(updateRunnable);
            stop.setVisibility(View.GONE);
            box.setVisibility(View.VISIBLE);
            time.setVisibility(View.INVISIBLE);
            name.setText("养锅完成");
        } else if (ac.jobmaster.steep_status == 0) {
            showDialog();
        }else {
            dismissDialog();
        }
        String timeText = "剩余时间: " + ac.jobmaster.remain_time + "s";
        Log.d(TAG,"time: " + timeText);
        time.setText(timeText);
    }

    private void showDialog() {
        // 如果弹窗已经显示，则不重复显示
        if (dialog != null && dialog.isShowing()) {
            return;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View dialogView = getLayoutInflater().inflate(R.layout.waitcook, null);
        builder.setView(dialogView);

        // 获取弹窗中的按钮和计时器文本
        final TextView countdownTextView = dialogView.findViewById(R.id.countdownTextView);
        timer = new CountDownTimer(60 * 1000,1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                countdownTextView.setText((millisUntilFinished / 1000) + "S");
            }
            @Override
            public void onFinish() {
                // 如果弹窗存在且正在显示，则关闭它
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                if ( timer != null ){
                    timer.cancel();
                    timer = null;
                }
                finish();
                Toast.makeText(PotCuringWaitActivity.this,"设备就位失败，请重试！",Toast.LENGTH_SHORT).show();
            }
        };
        timer.start();
        // 创建并显示弹窗
        dialog = builder.create();
        dialog.show();
        // 关键代码：设置窗口背景透明
        if (dialog.getWindow() != null) {
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        }
        // 关键代码：设置点击外部不可取消
        dialog.setCanceledOnTouchOutside(false);
        // 保存计时器和弹窗引用，以便在状态改变时停止计时器和关闭弹窗
        this.dialog = dialog;
        this.handler = handler;
    }

    // 关闭弹窗
    private void dismissDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
            if ( timer != null ){
                timer.cancel();
                timer = null;
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.pot_curing_wash_stop){
            String title = "提示";
            String content = "确认要终止养锅吗？";
            tools.showCustomDialog(this, title, content, new tools.OnDialogButtonClickListener() {
                @Override
                public void onConfirmClick() {
                    // 点击确认按钮后的逻辑
                    ToastUtils.show(PotCuringWaitActivity.this,"确认");
                    ac.Bringup_Stop();
                    stop.setVisibility(View.GONE);
                    box.setVisibility(View.VISIBLE);
                    time.setVisibility(View.INVISIBLE);
                    name.setText("养锅已终止");
                }
                @Override
                public void onCancelClick() {
                    // 点击取消按钮后的逻辑
                    ToastUtils.show(PotCuringWaitActivity.this,"取消");
                }
            });
        } else if (v.getId() == R.id.pot_curing_wash_back) {
            finish();
        } else if (v.getId() == R.id.pot_curing_wash_put_oil) {

        }
    }
}